<?php

namespace app\ask\controller;

use think\Controller;

class Post extends Controller
{
    protected $BusinessModel;
    protected $PostModel;
    protected $CateModel;
    protected $CollectModel;
    protected $PostCommentModel;
    protected $FriendModel;

    public function __construct()
    {
        parent::__construct();

        $this->BusinessModel = model('Business.Business');
        $this->PostModel = model('post.Post');
        $this->CateModel = model('post.Cate');
        $this->CollectModel = model('post.Collect');
        $this->PostCommentModel = model('post.Comment');
        $this->FriendModel = model('Friend');
    }

    public function index()
    {
        if ($this->request->isPost()) {
            $page = $this->request->param('page', 1, 'trim');
            $limit = $this->request->param('limit', 0, 'trim');
            $busid = $this->request->param('busid', 0, 'trim');
            $cateid = $this->request->param('cateid', 0, 'trim');
            $keyword = $this->request->param('keyword', '', 'trim');


            if (!$limit) {
                $limit = 10;
            }

            // 分页偏移量
            $offset = ($page - 1) * $limit;

            $where = [];

            if ($cateid) {
                $where['cateid'] = $cateid;
            }

            if ($busid) {
                $where['busid'] = $busid;
            }

            if (!empty($keyword)) {
                $where['title'] = ['like', "%$keyword%"];
            }

            $total = $this->PostModel
                ->where($where)
                ->count();

            $list = $this->PostModel
                ->with(['cate', 'business'])
                ->where($where)
                ->order('id', 'desc')
                ->limit($offset, $limit)
                ->select();

            if (!empty($list)) {
                $list = json_decode(json_encode($list), true);

                foreach ($list as $k => $v) {
                    $list[$k]['business'] = [
                        'id'          => $v['business']['id'],
                        'avatar_text' => $v['business']['avatar_text'],
                        'nickname'    => $v['business']['nickname'],
                    ];
                }
            }

            // myPrinf($list[0]);exit;

            $this->success('返回帖子数据', null, ['list' => $list ?? [], 'total' => $total]);
        }
    }

    // 查询帖子分类
    public function cate()
    {
        $list = $this->CateModel->order('weigh', 'asc')->select();

        if ($list) {
            $this->success('帖子分类', null, $list);
            exit;
        } else {
            $this->error('无帖子分类');
            exit;
        }
    }

    // 发布帖子
    public function add()
    {
        $title = $this->request->param('title', '', 'trim');
        $content = $this->request->param('content', '', 'trim');
        $point = $this->request->param('point', 0, 'intval');
        $cateid = $this->request->param('cateid', 0, 'trim');
        $busid = $this->request->param('busid', 0, 'trim');

        //确保用户是否存在
        $business = $this->BusinessModel->find($busid);

        if (!$business) {
            $this->error('用户不存在');
            exit;
        }

        if ($point < 0) {
            $this->error('积分不能为负数');
            exit;
        }

        $newPoint = bcsub($business['point'], $point);

        if ($newPoint < 0) {
            $this->error('您的积分不足');
            exit;
        }

        // 开始事务
        $this->PostModel->startTrans();
        $this->BusinessModel->startTrans();

        $data = [
            'title' => $title,
            'content' => $content,
            'point' => $point,
            'busid' => $busid,
            'cateid' => $cateid,
            'status' => '0',
        ];

        $postRes = $this->PostModel->validate('common/Post/Post')->save($data);

        if ($postRes === false) {
            $this->error($this->PostModel->getError());
            exit;
        }

        // 更新用户积分
        $busData = [
            'id' => $busid,
            'point' => $newPoint,
        ];

        $busRes = $this->BusinessModel->isUpdate(true)->save($busData);

        if ($busRes === false) {
            $this->PostModel->rollback();
            $this->error($this->BusinessModel->getError());
            exit;
        }

        if ($postRes === false || $busRes === false) {
            $this->PostModel->rollback();
            $this->BusinessModel->rollback();
            $this->error('发布失败');
            exit;
        } else {
            $this->BusinessModel->commit();
            $this->PostModel->commit();
            $this->success('发布成功', '/pages/post/info', ['postid' => $this->PostModel->id]);
            exit;
        }
    }

    // 修改帖子
    public function edit()
    {
        $id = $this->request->param('id', 0, 'trim');
        $title = $this->request->param('title', '', 'trim');
        $content = $this->request->param('content', '', 'trim');
        $point = $this->request->param('point', 0, 'intval');
        $cateid = $this->request->param('cateid', 0, 'trim');
        $busid = $this->request->param('busid', 0, 'trim');

        //确保用户是否存在
        $business = $this->BusinessModel->find($busid);

        if (!$business) {
            $this->error('用户不存在');
            exit;
        }

        $post = $this->PostModel->find($id);

        if (!$post) {
            $this->error('帖子不存在');
            exit;
        }

        if ($post['status'] === '1') {
            $this->error('您的帖子已解决，不能修改了哦');
            exit;
        }

        if ($point < 0) {
            $this->error('积分不能为负数');
            exit;
        }

        if ($point < $post['point']) {
            $this->error('积分不能低于原积分');
            exit;
        }

        // 把用户的积分加上修改的悬赏积分
        $originPoint = bcadd($business['point'], $post['point']);

        $newPoint = bcsub($originPoint, $point);

        if ($newPoint < 0) {
            $this->error('您的积分不足');
            exit;
        }

        // 开始事务
        $this->PostModel->startTrans();
        $this->BusinessModel->startTrans();

        $data = [
            'id'    => $id,
            'title' => $title,
            'content' => $content,
            'point' => $point,
            'busid' => $busid,
            'cateid' => $cateid,
        ];

        $postRes = $this->PostModel->validate('common/Post/Post')->isUpdate(true)->save($data);

        if ($postRes === false) {
            $this->error($this->PostModel->getError());
            exit;
        }

        // 更新用户积分
        $busData = [
            'id' => $busid,
            'point' => $newPoint,
        ];

        $busRes = $this->BusinessModel->isUpdate(true)->save($busData);

        if ($busRes === false) {
            $this->PostModel->rollback();
            $this->error($this->BusinessModel->getError());
            exit;
        }

        if ($postRes === false || $busRes === false) {
            $this->PostModel->rollback();
            $this->BusinessModel->rollback();
            $this->error('修改失败');
            exit;
        } else {
            $this->BusinessModel->commit();
            $this->PostModel->commit();
            $this->success('修改成功', '/pages/post/info', ['postid' => $this->PostModel->id]);
            exit;
        }
    }

    // 帖子详情
    public function info()
    {
        $postid = $this->request->param('postid', 0, 'trim');
        $busid = $this->request->param('busid', 0, 'trim');

        $post = $this->PostModel->with(['business', 'cate'])->find($postid);

        if (!$post) {
            $this->error('暂无帖子信息');
            exit;
        }

        // myPrinf(array_keys(collection($post)->toarray()));exit;

        $business = $this->BusinessModel->find($busid);

        // 如果有找到用户信息
        if ($business) {
            // 查询收藏的状态
            $collect = model('post.Collect')->where(['postid' => $postid, 'busid' => $busid])->find();

            if ($collect) {
                // 追加自定义数组元素
                $post['collect'] = true;
            }

            // 追加是否关注
            $friend = $this->FriendModel->where(['busid' => $busid, 'fansid' => $post['busid']])->find();

            if ($friend) {
                $post['friend'] = true;
                $post['friend_text'] = $friend['createtime_text'];
            }
        }

        $post = $post->toArray();

        $post['business'] = filter_property($post['business'], ['id', 'avatar_text', 'nickname']);

        $this->success('返回帖子信息', null, $post);
        exit;
    }

    // 收藏
    public function collect()
    {
        $postid = $this->request->param('postid', 0, 'trim');
        $busid = $this->request->param('busid', 0, 'trim');

        $business = $this->BusinessModel->find($busid);

        if (!$business) {
            $this->error('用户不存在');
            exit;
        }

        $post = $this->PostModel->find($postid);

        if (!$post) {
            $this->error('帖子不存在');
            exit;
        }

        $collect = $this->CollectModel->where(['postid' => $postid, 'busid' => $busid])->find();

        if ($collect) {
            $res = $this->CollectModel->where(['id' => $collect['id']])->delete();

            if ($res === false) {
                $this->error('取消收藏失败');
                exit;
            } else {
                $this->success('取消收藏成功');
                exit;
            }
        } else {
            $res = $this->CollectModel->save(['postid' => $postid, 'busid' => $busid]);

            if ($res === false) {
                $this->error('收藏失败');
                exit;
            } else {
                $this->success('收藏成功');
                exit;
            }
        }
    }

    // 删除
    public function del()
    {
        $postid = $this->request->param('postid', 0, 'trim');
        $busid = $this->request->param('busid', 0, 'trim');

        $business = $this->BusinessModel->find($busid);

        if (!$business) {
            $this->error('用户不存在');
            exit;
        }

        $post = $this->PostModel->find($postid);

        if (!$post) {
            $this->error('帖子不存在');
            exit;
        }

        if ($post['busid'] !== $business['id']) {
            $this->error('非法操作');
            exit;
        }

        $this->PostModel->startTrans();
        $this->PostCommentModel->startTrans();

        $postRes = $this->PostModel->where(['id' => $postid])->delete();

        if ($postRes === false) {
            $this->error($this->PostModel->getError());
            exit;
        }

        $commentRes = $this->PostCommentModel->where(['postid' => $postid])->delete();


        if ($commentRes === false) {
            $this->PostModel->rollback();
            $this->error($this->PostCommentModel->getError());
            exit;
        }

        if ($postRes === false || $commentRes === false) {
            $this->PostModel->rollback();
            $this->PostCommentModel->rollback();
            $this->error('删除失败');
            exit;
        } else {
            $this->PostCommentModel->commit();
            $this->PostModel->commit();

            $this->success('删除成功');
            exit;
        }
    }
}
